package com.conversationboard.controller;

import java.io.IOException;
import java.security.Principal;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.authenticator.AuthenticationCookie;
import com.conversationboard.cache.newanswers.NewAnswersThread;
import com.conversationboard.config.Configuration;
import com.conversationboard.model.User;
import com.conversationboard.site.Site;

@WebServlet(name = "SiteNewQuestionsControllerServlet", urlPatterns = "/SiteNewQuestionsControllerServlet")
public class SiteNewQuestionsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = -4021056265128695732L;


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			Principal principal = request.getUserPrincipal();

			/* Auto login */

			if (principal == null) {
				if (AuthenticationCookie.getUserName(request) != null) {
					response.sendRedirect(Configuration.getInstance().getRoot() + "/LoginControllerServlet?autologin=true&referrer=SiteNewQuestionsControllerServlet");
					return;
				}
			}

			String userId = null;

			if (request.getUserPrincipal() != null) {
				userId = request.getUserPrincipal().getName();
			}

			User user = User.get(userId);
			List<NewAnswersThread> newQuestions = Site.getSiteNewQuestions(0, 50);

			request.setAttribute("newquestions", newQuestions);
			request.setAttribute("user", user);

			RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/viewsiterecentquestions.jsp");
			dispatcher.forward(request, response);

		} catch (SQLException e) {
			throw new ServletException(e);
		}

	}

}
